package com.mobile.service.impl;

import com.itheima.common.constant.MessageConstant;
import com.itheima.common.constant.RedisMessageConstant;
import com.mobile.pojo.LoginDTO;
import com.mobile.service.MemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @author Encounter
 * @date 2024/10/15 15:11<br/>
 */
@Service
public class MemberServiceImpl implements MemberService
    {
        @Autowired
        private RedisTemplate redisTemplate;
        
        /**
         * 登录
         *
         * @param loginDTO 登录 DTO
         * @return boolean
         */
        @Override
        public boolean login(LoginDTO loginDTO)
            {
                //获取登陆手机号以及验证码
                String telephone = loginDTO.getTelephone();
                String validateCode = loginDTO.getValidateCode();
                
                if (telephone == null || validateCode == null || telephone.isEmpty() || validateCode.isEmpty())
                    {
                        throw new RuntimeException(MessageConstant.TELEPHONE_VALIDATECODE_NOTNULL);
                    }
                
                //获取缓存中的验证码
                String key = RedisMessageConstant.SENDTYPE_LOGIN + ":" + telephone;
                Long ttl = redisTemplate.getExpire(key, TimeUnit.SECONDS);
                if (ttl != null && ttl > 0)
                    {
                        ValueOperations valueOperations = redisTemplate.opsForValue();
                        String code = (String) valueOperations.get(key);
                        //返回登陆结果
                        return code != null && code.equals(validateCode);
                    }
                else
                    {
                        //验证码不存在或已失效，抛出验证码错误异常
                        throw new RuntimeException(MessageConstant.VALIDATECODE_ERROR);
                    }
            }
    }
